import React, { useContext, useReducer } from "react";

/*
 * @Author: Wxx
 * @Date: 2022-02-22 17:25:49
 * @LastEditors: Wxx
 * @LastEditTime: 2022-02-22 17:33:40
 * @Description:
 */
const reducers = (prevState, action) => {
  switch (action.type) {
    case "change-a":
      return {
        ...prevState,
        a: prevState.a + action.value,
      };
    case "change-b":
      return {
        ...prevState,
        b: prevState.b + action.value,
      };
    default:
      return prevState;
  }
};
const initstate = {
  a: "冰墩墩",
  b: "雪融融",
};
const MyContext = React.createContext();
export default function App() {
  const [state, dispatch] = useReducer(reducers, initstate);
  return (
    <MyContext.Provider
      value={{
        state,
        dispatch,
      }}
    >
      <div>
        <Child1 />
        <Child2 />
        <Child3 />
      </div>
    </MyContext.Provider>
  );
}

function Child1() {
  const { dispatch } = useContext(MyContext);
  return (
    <div>
      <button
        onClick={() => {
          dispatch({
            type: "change-a",
            value: "真可爱",
          });
        }}
      >
        改变a
      </button>
      <button
        onClick={() => {
          dispatch({
            type: "change-b",
            value: "真可爱",
          });
        }}
      >
        改变b
      </button>
    </div>
  );
}
function Child2() {
  const { state } = useContext(MyContext);
  return <div>a的值是:{state.a}</div>;
}
function Child3() {
  const { state } = useContext(MyContext);
  return <div>b的值是:{state.b}</div>;
}
